import { getUserChannels, getChannels, editUserChannels } from '@/api'

export default {
  state: {
    channels: [],
    userChannel: [],
    activeId: 0
  },
  getters: {
    moreChannel (state) {
      return state.channels.filter(channel => {
        if (state.userChannel.some(userChannel => userChannel.id === channel.id)) {
          return false
        } else return channel
      })
    }
  },
  mutations: {
    setChannel (state, { type, data }) {
      if (type === 'user') {
        state.userChannel = data
      } else if (type === 'all') {
        state.channels = data
      }
    }
  },
  actions: {
    async getChannel ({ commit }) {
      // 获取所有频道
      const { data: { data: { channels: allChannels } } } = await getChannels()
      // 获取用户频道
      const { data: { data: { channels: userChannels } } } = await getUserChannels()
      const packUserChannels = {
        type: 'user',
        data: userChannels
      }
      commit('setChannel', packUserChannels)
      const packChannels = {
        type: 'all',
        data: allChannels
      }
      commit('setChannel', packChannels)
    },
    async uploadChannel ({ state, commit }, channels) {
      // 提交更新用户频道
      editUserChannels(channels)
      const temp = []
      channels.forEach(channel => {
        const res = state.channels.find(item => item.id === channel.id)
        if (res) {
          temp.push(res)
        }
      })
      const packUserChannels = {
        type: 'user',
        data: temp
      }
      commit('setChannel', packUserChannels)
    }
  }
}
